/*
 * SearchResults.fx
 * Author: Yu Min-ting
 * Created on 2009-7-22, 11:05:44
 */

package com.sjtu.fx.book;

import javafx.scene.CustomNode;


import javafx.scene.image.Image;




import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.Label;
import javafx.scene.layout.Flow;
import javafx.scene.layout.Tile;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import com.sjtu.fx.tools.Panel;
import java.lang.Integer;


import javafx.stage.Alert;

import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import com.sjtu.fx.tools.SwingTextArea;

import java.lang.System;

import javafx.io.http.HttpRequest;
import java.io.DataInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONArray;
import org.json.JSONObject;

import com.sjtu.fx.tools.UIAlert;


public class SearchResults extends CustomNode {
    var panel:Panel;
//    public var results:Results[];
    public var url:String[];
    public var author:String[];
    public var publisher:String[];
    public var title:String[];
    public var bookid:String[];
    var pageNumber:Integer;
    var pageCurrent:Integer;

    var resultInfo = Label {
            translateX:30 translateY:50
            text: bind "Total {title.size()} Items are found"
            font: Font {size:12 name: "Verdana Bold"}
            textFill: Color.rgb(11,51,60)
        }
    var  pages:Flow =  Flow {
                     id : "pages"
                     translateX:80 translateY:490
                     width: 300
                     height:20
                     hgap: 20 // horizontal gap between nodes in a row
                     hpos: HPos.CENTER

                }
    public var Images = Tile{
                    translateX:25 translateY:80
                    hgap:5
                    vgap:25
                    tileWidth:205
                    columns:2
                    nodeHPos: HPos.CENTER
    //               content:
    /*                for (i in[1..6])
                    Group {
                        content: [
                              HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                            //todo
                                        }
                                        image: bind if(images[6*(pageCurrent-1)+i-1]!=null) images[6*(pageCurrent-1)+i-1] else null
                                    },
                                    SwingTextArea{
                                        text: bind if(6*(pageCurrent-1)+i-1<title.size())
                                        {"{6*(pageCurrent-1)+i-1}true {title[6*(pageCurrent-1)+i-1]} \n·By {author[6*(pageCurrent-1)+i-1]}\n·Book Publisher:\n{publisher[6*(pageCurrent-1)+i-1]}"}
                                        else""
                                        editable:false

                                    }
                                ]
                             }
                       ]

                    }
     */           } //end of Tile

      var alert = UIAlert {
         translateX:75
         translateY:200
         title:"ERROR"
         content:"Please input entire information"
         width:280
         height:120
         visible:false
         opacity:0.9
     }

     override protected function create() : Node {
        setPage();
        Group{
            content:[
                 panel = Panel {
                    width:    465
                    height:   550
                    title:    "Search Results"
                    translateX: 0
                    translateY: 0
                },resultInfo,
               Images,
                pages,alert
           ]
        }
     }

    function setPage(){
        pageNumber =  title.size()/6;
        if(title.size() mod 6 >0) pageNumber++;
        pageCurrent = 1;
        var contents:Node[] ;
        var pre = Hyperlink {
                text: "<Previous"
                action: function() {
                    if(pageCurrent>1){
                        pageCurrent--;
                        pageNumber =  title.size()/6;
                        for (i in[1..6]){
                            Images.content[0] = null;
                        }
                        var index :Integer = (pageCurrent-1)*6;
                        while(index<pageCurrent*6 and index>=(pageCurrent-1)*6){
                      //      System.out.println("index:{index}");
                            var box:Group = Group{
                        id: index.toString() 
                        content: [
                            HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                            setBorrowBookPage(Integer.parseInt(bookid.get(Integer.parseInt(box.id)).toString()));
                                        }

                                        image: Image{url: "{__DIR__}{url[index]}.jpg" }
                                    },
                                    SwingTextArea{
                                        text:
                                        "{title[index]} \n·By {author[index]}\n·Book Publisher:\n{publisher[index]}"
                                        editable:false
                                    }
                                ]
                             }]};
                             index++;
                             Images.content[index-6*(pageCurrent-1)] = box;
                        }
                        }else{
                            alert.title = "Inform";
                            alert.content = "The first page";
                            alert.visible = true;
                            //Alert.inform("the first page");
                        }
                }
            }
        var next = Hyperlink {
                text: "Next>"
                action: function() {
                    pageNumber =  title.size()/6;
                    System.out.println("pageCurrent:{pageCurrent}");
                    System.out.println("pageNumber:{pageNumber}");
                    if(pageCurrent<=pageNumber){
                        pageCurrent++;
                        for (i in[1..6]){
                            Images.content[0] = null;
                        }
                        var index :Integer = (pageCurrent-1)*6;
                        while(index<title.size() and index<pageCurrent*6){
//                            System.out.println("index{index}");
//                            System.out.println("index-6*pageCurrent{index-6*(pageCurrent-1)}");
                            var box:Group = Group{
                                id: index.toString()
                        content: [
                            HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                            setBorrowBookPage(Integer.parseInt(bookid.get(Integer.parseInt(box.id)).toString()));
                                        }
                                       image: Image{url: "{__DIR__}{url[index]}.jpg" }
                                    },
                                    SwingTextArea{
                                        text:
                                        "{title[index]} \n·By {author[index]}\n·Book Publisher:\n{publisher[index]}"
                                        editable:false
                                    }
                                ]
                             }]};
                             index++;
                             Images.content[index-6*(pageCurrent-1)] = box;
                        }
                        }else{
                            alert.content = "The last page";
                            alert.visible = true;
                           // Alert.inform("the last page");
                        }
                }
            }
        var start = Hyperlink {
                text: "<<First"
                action: function() {
                    System.out.println(pageCurrent);
                    if(pageCurrent == 1){
                         alert.content = "Already first page";
                         alert.visible = true;
                         //Alert.inform("already first page!");
                    }
                    else{
                    pageCurrent = 1;
                    for (i in[1..6]){
                            Images.content[0] = null;
                        }
                    var index:Integer = 0;
                    while(index<title.size() and index<6){
                        var box:Group = Group{
                            id: index.toString()
                        content: [
                            HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                            setBorrowBookPage(Integer.parseInt(bookid.get(Integer.parseInt(box.id)).toString()));
                                        }
                                        image: Image{url: "{__DIR__}{url[index]}.jpg" }
                                    },
                                    SwingTextArea{
                                        text:
                                        "{title[index]} \n·By {author[index]}\n·Book Publisher:\n{publisher[index]}"
                                        editable:false
                                    }
                                ]
                             }]};
                             index++;
                             Images.content[index] = box;
                    }
                    }
                }
            }
        var end = Hyperlink {
                text: "Final>>"
                action: function() {
                    pageNumber =  title.size()/6;
                    if(pageCurrent == pageNumber+1){
                         alert.content = "Already last page";
                         alert.visible = true;
                         //Alert.inform("already last page!");
                    }
                    else{
                    pageCurrent = pageNumber+1;
                    for (i in[1..6]){
                            Images.content[0] = null;
                        }
                    var index:Integer = pageNumber*6;
                    while(index<title.size()){
                        System.out.println("index:{index}");
                        var box:Group = Group{
                            id:index.toString()
                        content: [
                            HBox{
                                spacing: 10
                                content:[
                                    ImageView {
                                        onMouseClicked: function( e: MouseEvent ):Void {
                                            setBorrowBookPage(Integer.parseInt(bookid.get(Integer.parseInt(box.id)).toString()));
                                        }
                                        image: Image{url: "{__DIR__}{url[index]}.jpg" }
                                    },
                                    SwingTextArea{
                                        text:
                                        "{title[index]} \n·By {author[index]}\n·Book Publisher:\n{publisher[index]}"
                                        editable:false
                                    }
                                ]
                             }]};
                             index++;
                             Images.content[index] = box;
                    }
                    }
                }
            }
         contents[0] = start;
         contents[1] = pre;
         contents[2] = next;
         contents[3] = end;
         pages.content = contents;


    }

public function setBorrowBookPage(id:Integer){
    HttpRequest {
        method:HttpRequest.POST
        location:"http://localhost:8764/JavaFXBack/BookDetail"
       onOutput: function(os:OutputStream) {
            try {
                var json:JSONObject = JSONObject{};
                json.put("bookId",id);
                System.out.println("Here{id}");
                var temp:String = "obj={json.toString()}";
         //       System.out.println(temp);
                os.write(temp.getBytes());
                os.flush();
            } finally {
                os.close();
            }
        }
        onInput: function(is: InputStream) {
            try {
                def data:DataInputStream = new DataInputStream(is);
                var json:JSONObject = JSONObject{};
                var result:String = data.readLine();
                System.out.println(result);
                json = new JSONObject(result);
                var description:String = json.getString("description");
                var score:Integer = json.getInt("score");
                var labels:JSONArray = json.getJSONArray("labels");
                var bookInfo:JSONArray = json.getJSONArray("booklendinfo");
                
            } finally {
                is.close();
            }
        }
    }.start();
}
}
